﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using 第二课堂评审系统.Models;

namespace 第二课堂评审系统.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class TeacherController : ControllerBase
    {
        private readonly _MyDbContext Db;
        private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;
        public TeacherController(_MyDbContext db, IOptionsSnapshot<JWTSettings> jwtSettingsOpt)
        {
            Db = db;
            this.jwtSettingsOpt = jwtSettingsOpt;
        }

        #region 获取待审核的作品
        [HttpGet]
        public ActionResult getWorks()
        {
            using _MyDbContext Context = new _MyDbContext();
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            /*User user = Context.Users.Where(u => u.Id.ToString() == UID).FirstOrDefault()!;*/
            //获取所有未审核的作品
            List<Project> projects = Context.Projects.Include(o => o.Partnar).ThenInclude(o=>o.members).Where(o => o.isPassed==null&&o.Partnar.guideTeacher.StuNum==Convert.ToInt32( UID)).ToList();
            List<object> listJs = new List<object>();
            if (projects != null && projects.Count() > 0)
            {
               
                foreach (Project project in projects)
                {
                    if(project.Name==null||project.Name=="") continue;
                    Partnar partnar = project.Partnar!;
                    //将成员名包装为字符串数组
                    List<string> listMember = new List<string>();
                    if (partnar != null && partnar.members != null)
                    {
                        foreach (User m in partnar.members)
                        {
                            listMember.Add(m.Name);
                        }
                    }
                    //获取指导老师
                    //处理返回结果
                    listJs.Add(new
                    {
                        itemId = project.Id,
                        itemName = project.Name,
                        groupType = partnar == null || partnar.searchDirection == null ? null : partnar.searchDirection,
                        itemType = partnar == null || partnar.projectDirection == null ? null : partnar.projectDirection.Split(","),
                        groupName = partnar == null || partnar.Name == null ? null : partnar.Name,
                        groupMembers = listMember,
                        leaderTeacher = partnar == null || partnar.guideTeacher == null ? null : partnar.guideTeacher.Name,
                        Counsellor = partnar == null || partnar.counsellor == null ? null : partnar.counsellor,
                        itemContent = project.Description,
                        Finished = project.projectState==6,
                        S_or_F = false,
                    });
                }
            }
            return new JsonResult(listJs);
        }
        #endregion



        #region 获取小组信息
        [HttpGet]
        public ActionResult getGroupInfo()
        {
            using _MyDbContext Context=new _MyDbContext();
            //获取所有小组
            List<Partnar> partnars= Context.Partnars.Include(o=>o.members)!.ThenInclude(o=>o.Roles).ToList();
            //返回结构
            List<object> listJs= new List<object>();
           
            if(partnars!=null)
            {
                foreach(var partnar in partnars) {
                    //获得组长
                    List<User> listMembers = partnar.members!;
                    string HeaderName = listMembers.Where(o =>o.Roles==null?false:o.Roles[0].Name=="S1").FirstOrDefault()!.Name;
                    
                    //返回参数
                    listJs.Add(new
                    {
                        groupName= partnar.Name,
                        inviteCode=partnar.inviteNum,
                        groupAvatar= partnar.avatorUrl,
                        groupHeader= HeaderName,
                        groupMembers= partnar.members!.Select(o => new {avatarUrl = o.avatar,name = o.Name}),
                        groupId= partnar.Id
                        });
                }
            }
            return new JsonResult(listJs);
        }

        #endregion



        #region 审核通过请求
        [HttpPost]
        public ActionResult workSuccess([FromBody]string itemId)
        {
            using _MyDbContext Context=new _MyDbContext();
            Project project = Context.Projects.Where(o=>o.Id==Convert.ToInt32(itemId)).FirstOrDefault()!;
            if (project == null)
            {
                return BadRequest("操作失败，不存在该项目");
            }
            project.isPassed= true;
            Context.SaveChangesAsync();
            return Ok("操作成功");
        }
        #endregion



        #region 审核通过失败
        [HttpPost]
        public ActionResult workFailed([FromBody]string itemId)
        {
            using _MyDbContext Context = new _MyDbContext();
            Project project = Context.Projects.Where(o => o.Id == Convert.ToInt32(itemId)).FirstOrDefault()!;
            if (project == null)
            {
                return BadRequest("操作失败，不存在该项目");
            }
            project.isPassed = false;
            Context.SaveChangesAsync();
            return Ok("操作成功");
        }
        #endregion

        public record scores(int score1 ,int score2,int score3, int score4, int score5, int score6, int score7);
        public record StuScores(string itemId,int session,scores scores);
        [HttpPut]//提交分数
        public ActionResult score([FromBody] StuScores stuScores)
        {
            Partnar ? partnar=Db.Partnars.Where(p=>p.Id.ToString()==stuScores.itemId).ToList().SingleOrDefault();
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u=>u.JudgePre).Include(u=>u.JudgeFin).Include(u=>u.achievements).ToList().SingleOrDefault()!;

            if(stuScores.session==0)
            {
                if (Db.Achievements.Where(u => u.Partnar.Id.ToString() == stuScores.itemId && u.Judge.Id.ToString() == UID && u.Session == 0).ToList().SingleOrDefault() == null)//首次提交成绩且为初赛
                {
                    Achievement achievement = new Achievement();
                    achievement.chooseArticle = stuScores.scores.score1;
                    achievement.developWay = stuScores.scores.score2;
                    achievement.requireAnalysis = stuScores.scores.score3;
                    achievement.word = stuScores.scores.score4;
                    achievement.Function = stuScores.scores.score5;
                    achievement.technology = stuScores.scores.score6;
                    achievement.reply = stuScores.scores.score7;
                    achievement.total = stuScores.scores.score1 + stuScores.scores.score2 + stuScores.scores.score3 + stuScores.scores.score4 + stuScores.scores.score5 + stuScores.scores.score6 + stuScores.scores.score7;
                    achievement.Session = stuScores.session;
                    achievement.Partnar = partnar!;
                    //将成绩保存到小组
                    if (partnar!.achievements == null)
                    {
                        List<Achievement> achievements = new List<Achievement>();
                        partnar.achievements = achievements;
                        partnar.achievements.Add(achievement);
                    }
                    else
                    {
                        partnar.achievements.Clear();
                        partnar.achievements.Add(achievement);

                    }

                    //成绩绑定比赛
                    if (stuScores.session == 0)//初赛
                    {
                        Preliminary preliminary = Db.Preliminaries.Where(p => p.Id == user.JudgePre!.Id).Include(p => p.Achievements).ToList().Single();
                        achievement.Preliminary = preliminary;
                        if (preliminary.Achievements == null)
                        {
                            List<Achievement> achievements1 = new List<Achievement>();
                            preliminary.Achievements = achievements1;

                            preliminary.Achievements.Add(achievement);

                        }
                        else
                        {

                            preliminary.Achievements.Add(achievement);
                        }
                    }
                    else//决赛
                    {
                        Final final = Db.Finals.Where(p => p.Id == user.JudgeFin!.Id).Include(p => p.Achievements).ToList().Single();
                        achievement.final = final;
                        if (final.Achievements == null)
                        {
                            List<Achievement> achievements1 = new List<Achievement>();
                            final.Achievements = achievements1;
                            final.Achievements.Add(achievement);

                        }
                        else
                        {
                            final.Achievements.Add(achievement);
                        }
                    } 
                    achievement.Judge = user;
                    //成绩绑定到评委
                    if (user.achievements == null)
                    {
                        List<Achievement> achievements = new List<Achievement>();
                        user.achievements = achievements;
                        user.achievements.Add(achievement);
                    }
                    else
                    {
                        user.achievements.Add(achievement);
                    }
                    Db.Achievements.Add(achievement);
                }
                else
                {
                    Achievement achievement = Db.Achievements.Where(u => u.Partnar.Id.ToString() == stuScores.itemId && u.Judge.Id.ToString() == UID && u.Session == 0).ToList().Single();
                    achievement.chooseArticle = stuScores.scores.score1;
                    achievement.developWay = stuScores.scores.score2;
                    achievement.requireAnalysis = stuScores.scores.score3;
                    achievement.word = stuScores.scores.score4;
                    achievement.Function = stuScores.scores.score5;
                    achievement.technology = stuScores.scores.score6;
                    achievement.reply = stuScores.scores.score7;
                    achievement.total = stuScores.scores.score1 + stuScores.scores.score2 + stuScores.scores.score3 + stuScores.scores.score4 + stuScores.scores.score5 + stuScores.scores.score6 + stuScores.scores.score7;
                }
            }
            else {
                if (Db.Achievements.Where(u => u.Partnar.Id.ToString() == stuScores.itemId && u.Judge.Id.ToString() == UID && u.Session == 1).ToList().SingleOrDefault() == null)//首次提交成绩且为决赛
                {
                    Achievement achievement = new Achievement();
                    achievement.chooseArticle = stuScores.scores.score1;
                    achievement.developWay = stuScores.scores.score2;
                    achievement.requireAnalysis = stuScores.scores.score3;
                    achievement.word = stuScores.scores.score4;
                    achievement.Function = stuScores.scores.score5;
                    achievement.technology = stuScores.scores.score6;
                    achievement.reply = stuScores.scores.score7;
                    achievement.total = stuScores.scores.score1 + stuScores.scores.score2 + stuScores.scores.score3 + stuScores.scores.score4 + stuScores.scores.score5 + stuScores.scores.score6 + stuScores.scores.score7;
                    achievement.Session = stuScores.session;
                    achievement.Partnar = partnar!;
                    //将成绩保存到小组
                    if (partnar!.achievements == null)
                    {
                        List<Achievement> achievements = new List<Achievement>();
                        partnar.achievements = achievements;
                        partnar.achievements.Add(achievement);
                    }
                    else
                    {
                        partnar.achievements.Add(achievement);

                    }

                    //成绩绑定比赛
                    if (stuScores.session == 0)//初赛
                    {
                        Preliminary preliminary = Db.Preliminaries.Where(p => p.Id == user.JudgePre!.Id).Include(p => p.Achievements).ToList().Single();
                        achievement.Preliminary = preliminary;
                        if (preliminary.Achievements == null)
                        {
                            List<Achievement> achievements1 = new List<Achievement>();
                            preliminary.Achievements = achievements1;

                            preliminary.Achievements.Add(achievement);

                        }
                        else
                        {

                            preliminary.Achievements.Add(achievement);
                        }
                    }
                    else//决赛
                    {
                        Final final = Db.Finals.Where(p => p.Id == user.JudgeFin!.Id).Include(p => p.Achievements).ToList().Single();
                        achievement.final = final;
                        if (final.Achievements == null)
                        {
                            List<Achievement> achievements1 = new List<Achievement>();
                            final.Achievements = achievements1;
                            final.Achievements.Add(achievement);

                        }
                        else
                        {
                            final.Achievements.Add(achievement);
                        }
                    }
                    achievement.Judge = user;
                    //成绩绑定到评委
                    if (user.achievements == null)
                    {
                        List<Achievement> achievements = new List<Achievement>();
                        user.achievements = achievements;
                        user.achievements.Add(achievement);
                    }
                    else
                    {
                        user.achievements.Add(achievement);
                    }
                    Db.Achievements.Add(achievement);
                }
                else
                {
                    Achievement achievement = Db.Achievements.Where(u => u.Partnar.Id.ToString() == stuScores.itemId && u.Judge.Id.ToString() == UID && u.Session == 1).ToList().Single();
                    achievement.chooseArticle = stuScores.scores.score1;
                    achievement.developWay = stuScores.scores.score2;
                    achievement.requireAnalysis = stuScores.scores.score3;
                    achievement.word = stuScores.scores.score4;
                    achievement.Function = stuScores.scores.score5;
                    achievement.technology = stuScores.scores.score6;
                    achievement.reply = stuScores.scores.score7;
                    achievement.total = stuScores.scores.score1 + stuScores.scores.score2 + stuScores.scores.score3 + stuScores.scores.score4 + stuScores.scores.score5 + stuScores.scores.score6 + stuScores.scores.score7;
                }
            }
            Db.SaveChanges();
            return Ok();
        }



        #region 获得初赛教室信息
        [HttpGet]
        public ActionResult getOriginPrograms()
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取当前评委用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Context.Users.Where(u=>u.StuNum.ToString()==UID).Include(t=>t.JudgePre).FirstOrDefault()!;
            if (user.JudgePre == null)
            {
                return BadRequest("还没有决赛信息");
            }
            //获取当前评委的初赛表
            Preliminary preliminary = Context.Preliminaries.Include(p => p.judgesList)
                .Include(p=>p.Partnars).Include(p => p.JoinPartnars).ThenInclude(p=>p.project).Where(p => p.Id == user.JudgePre.Id).FirstOrDefault();

            if (preliminary != null)
            {
                //获取所有老师
                var teacher = preliminary.judgesList.Select(p => new { sno = p.StuNum, sname = p.Name });

                //获取所有小组
                List<Partnar> partnars = preliminary.Partnars==null?null: preliminary.Partnars.ToList();
                partnars=partnars.Where(p=>p.project.Name!=null&&p.project.Name!="").ToList();
                var items = preliminary.JoinPartnars.Select(p => new { itemName = p.project.Name, isSignIn = partnars==null?false:partnars.Contains(p), itemId = p.project.Id });
                return new JsonResult(new {roomId=preliminary.classRoom,teacher,items});
            }
            else
            {
                return BadRequest("还没有初赛信息");
            }
        }
        #endregion


        #region 获得初赛待评审项目
        [HttpGet]
        public ActionResult getOriginItems()
        {
            using _MyDbContext Context= new _MyDbContext();
            //获取当前评委用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Context.Users.Where(u => u.StuNum.ToString() == UID).FirstOrDefault()!;
            //获取所有小组
            List<Partnar> partnarList = Context.Partnars.Include(p=>p.members).Include(p=>p.MyPreliminary).ThenInclude(p=>p.judgesList).Include(p=>p.project).Include(p=>p.guideTeacher).ToList();
            //获得当前评委的小组
           List<Partnar> partnars = partnarList.Where(p=>p.MyPreliminary!=null&&p.MyPreliminary.judgesList.Contains(user)).ToList();
            //构造返回参数
            List<object> result = new List<object>();
            if(partnars != null)
            {
                foreach(var p in partnars)
                {
                    string itemId = p.project.Id.ToString();
                    string itemName = p.project.Name;
                    string groupType =p.searchDirection;
                    string groupName =p.Name;
                    List<string> itemType = p.projectDirection==null?null:p.projectDirection.Split(",").ToList();
                    List<string> groupMembers = p.members.Select(u => u.Name).ToList();
                    string leaderTheacher = p.guideTeacher.Name;
                    string counsellor = p.counsellor;
                    string itemContent = p.project.Description;
                    Achievement a = Context.Achievements.Include(a=>a.Judge).Where(a=>a.Partnar==null?false:a.Partnar==p&&a.Session==0&&a.Judge.Id==user.Id).FirstOrDefault()!;
                    int score1 = a == null || a.chooseArticle == null ? 2 : a.chooseArticle;
                    int score2 = a == null || a.developWay == null ? 4 : a.developWay;
                    int score3 = a == null || a.requireAnalysis == null ? 4 : a.requireAnalysis;
                    int score4 = a == null || a.word == null ? 2 : a.word;
                    int score5 = a == null || a.Function == null ? 30 : a.Function;
                    int score6 = a == null || a.technology == null ? 12 : a.technology;
                    int score7 = a == null || a.reply == null ? 6 : a.reply;
                    var score = new { score1, score2, score3, score4, score5, score6, score7 };
                    result.Add(new {itemId,counsellor,itemName,groupType,groupName,itemType,groupMembers,leaderTheacher,itemContent,score,fileUrl = p.project.FileUrl });
                }
            }
            else
            {
                return BadRequest("还没有该评委的初赛项目信息");
            }
            return new JsonResult(result);
        }
        #endregion



        #region 获得决赛教室信息
        [HttpGet]
        public ActionResult getFinalPrograms()
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取当前评委用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Context.Users.Where(u => u.StuNum.ToString() == UID).Include(t => t.JudgeFin).FirstOrDefault()!;

            if (user.JudgeFin == null)
            {
                return BadRequest("还没有决赛信息");
            }
            //获取当前评委的初赛表
            Final final = Context.Finals.Include(f => f.judgesList)
                .Include(p => p.Partnars).Include(p => p.JoinPartnars).ThenInclude(p => p.project).Where(p => p.Id == user.JudgeFin.Id).FirstOrDefault();

            if (final != null)
            {
                //获取所有老师
                var teacher = final.judgesList.Select(p => new { sno = p.StuNum, sname = p.Name });

                //获取所有小组
                List<Partnar> partnars = final.Partnars == null ? null : final.Partnars.ToList();
                partnars = partnars.Where(p => p.project.Name != null && p.project.Name != "").ToList();

                var items = final.JoinPartnars.Select(p => new { itemName = p.project.Name, isSignIn = partnars == null ? false : partnars.Contains(p), itemId = p.project.Id });
                return new JsonResult(new { roomId = final.classRoom, teacher, items });
            }
            else
            {
                return BadRequest("还没有决赛信息");
            }
        }
        #endregion



        #region 获得决赛待评审项目
        [HttpGet]
        public ActionResult getFinalItems()
        {
            using _MyDbContext Context = new _MyDbContext();
            //获取当前评委用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Context.Users.Where(u => u.StuNum.ToString() == UID).FirstOrDefault()!;
            //获取所有小组
            List<Partnar> partnarList = Context.Partnars.Include(p => p.members).Include(p => p.MyFinal).ThenInclude(p => p.judgesList).Include(p => p.project).Include(p => p.guideTeacher).ToList();
            //获得当前评委的小组
            List<Partnar> partnars = partnarList.Where(p => p.MyFinal != null && p.MyFinal.judgesList.Contains(user)).ToList();
            //构造返回参数
            List<object> result = new List<object>();
            if (partnars != null)
            {
                foreach (var p in partnars)
                {
                    string itemId = p.project.Id.ToString();
                    string itemName = p.project.Name;
                    string groupType = p.searchDirection;
                    string groupName = p.Name;
                    List<string> itemType = p.projectDirection == null ? null : p.projectDirection.Split(",").ToList();
                    List<string> groupMembers = p.members.Select(u => u.Name).ToList();
                    string leaderTheacher = p.guideTeacher.Name;
                    string counsellor = p.counsellor;
                    string itemContent = p.project.Description;
                    Achievement a = Context.Achievements.Include(a => a.Judge).Where(a => a.Partnar == null ? false : a.Partnar == p && a.Session == 1 && a.Judge.Id == user.Id).FirstOrDefault()!;
                    int score1 = a == null || a.chooseArticle == null ? 2 : a.chooseArticle;
                    int score2 = a == null || a.developWay == null ? 4 : a.developWay;
                    int score3 = a == null || a.requireAnalysis == null ? 4 : a.requireAnalysis;
                    int score4 = a == null || a.word == null ? 2 : a.word;
                    int score5 = a == null || a.Function == null ? 30 : a.Function;
                    int score6 = a == null || a.technology == null ? 12 : a.technology;
                    int score7 = a == null || a.reply == null ? 6 : a.reply;
                    var score = new { score1, score2, score3, score4, score5, score6, score7 };
                    result.Add(new { itemId, counsellor, itemName, groupType, groupName, itemType, groupMembers, leaderTheacher, itemContent, score,fileUrl=p.project.FileUrl });
                }
            }
            else
            {
                return BadRequest("还没有该评委的决赛赛项目信息");
            }
            return new JsonResult(result);
        }
        #endregion



        #region 获取老师领导的小组
        [HttpGet]
        public ActionResult getGroups()
        {
            using _MyDbContext context = new();
            //获取当前老师用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            //获取该指导老师的小组
            List<Partnar> partnars= context.Partnars.Include(p => p.guideTeacher).Include(p => p.members).ThenInclude(p=>p.Roles).Include(p=>p.project).Where(p => p.guideTeacher.StuNum.ToString() == UID).ToList();
            if (partnars != null && partnars.Count > 0)
            {
                List<object> result = new List<object>();
                foreach (var partnar in partnars)
                {
                    string avatarUrl = "/PartnarAvatar/" + partnar.avatorUrl;
                    string state = partnar.project.projectState.ToString();
                    string inviteCode = partnar.inviteNum.ToString();
                    var zuYuan = partnar.members.Where(p => p.Roles[0].Name == "S0").Select(u => new { avatarUrl = "/Avatar/"+u.avatar, name = u.Name }).ToList();
                    var zuZhang = partnar.members.Where(p => p.Roles[0].Name == "S1").Select(u => new { avatarUrl = "/Avatar/" + u.avatar, name = u.Name }).FirstOrDefault();
                    string groupName = partnar.Name;
                    result.Add(new { avatarUrl, state, inviteCode, members = zuYuan, header=zuZhang,groupName });
                }
                return Ok(result);
            }
            return BadRequest("还没有指导的小组");
        }
        #endregion



        #region 获取老师的成绩表
        [HttpGet]
        public ActionResult getScores(string type)
        {
            using _MyDbContext context = new();
            //获取当前老师用户
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            //获取该评委所有的成绩表
            List<Achievement> AchievementList = context.Achievements.Include(a => a.Partnar).ThenInclude(p => p.project).Include(a => a.Judge).Where(a => a.Judge.StuNum.ToString() == UID&&a.Session==(type=="origin"?0:1)).ToList();
            if (AchievementList!=null&&AchievementList.Count>0)
            {
                List<object> result = new();
                foreach(Achievement a in AchievementList)
                {
                    int itemId = a.Partnar.project.Id;
                    string itemName = a.Partnar.project.Name;
                    int  score1=a.chooseArticle;
                    int  score2=a.developWay;
                    int  score3=a.requireAnalysis;
                    int  score4=a.word;
                    int  score5=a.Function;
                    int  score6=a.technology;
                    int  score7=a.reply;
                    var scores = new { score1, score2, score3, score4, score5, score6, score7 };
                    result.Add(new {itemId,itemName,type,scores});
                }
                
                 return new JsonResult(result);
            }   
            else
            {
                return BadRequest("你还没有小组");
            }
            
        }
        #endregion

        [HttpGet]
        public IActionResult getRanks()
        {
            var UID = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;
            User user = Db.Users.Where(u => u.StuNum.ToString() == UID).Include(u => u.allPartnar).ThenInclude(p=>p.project).ToList().SingleOrDefault()!;

            if(user.allPartnar==null)
            {
                return BadRequest("您没有参赛的小组");
            }


            var js = user.allPartnar.Select(a => new { itemName =a.project.Name, itemRank = a.project.Rank});

            return new JsonResult(js);
        }
    }
}
